﻿Imports System.Net
Imports System.Net.Sockets
Imports System.Windows.Forms

Public Class Form1

    Public Shared Sub Main()
        Application.Run(New Form1())

    End Sub
    ''' <summary>
    ''' 启动扫描
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text.Trim() = "" Then
            MessageBox.Show("数据不能为空")
        Else
            Dim ipAddress As String = "目标IP地址"
            Dim maxThreads As Integer = 100 ' 最大线程数

            Dim availablePorts As New List(Of Integer)()

            Dim tasks As New List(Of Task)()

            For port As Integer = 1 To 65535
                tasks.Add(Task.Run(Sub()
                                       Dim tcpClient As New TcpClient()
                                       Try
                                           tcpClient.Connect(ipAddress, port)
                                           availablePorts.Add(port)
                                           tcpClient.Close()
                                       Catch ex As SocketException
                                           RichTextBox1.AppendText("测试时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "端口未开放" & Environment.NewLine)
                                       End Try
                                   End Sub))

                If tasks.Count >= maxThreads Then
                    ' 当达到最大任务数时，等待所有任务完成
                    Await Task.WhenAll(tasks.ToArray())
                    tasks.Clear()
                End If
            Next

            ' 等待剩余的任务完成
            Await Task.WhenAll(tasks.ToArray())

            ' 输出可访问的端口
            RichTextBox1.AppendText("测试时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "端口开放" & Environment.NewLine)
            For Each port As Integer In availablePorts
                Console.WriteLine(port)
            Next
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        StartPosition = FormStartPosition.CenterScreen
    End Sub
    Private Sub AddTextToRichTextBox(text As String)
        If RichTextBox1.InvokeRequired Then
            RichTextBox1.Invoke(Sub() AddTextToRichTextBox(text))
        Else
            RichTextBox1.WordWrap = True
            RichTextBox1.AppendText(text & Environment.NewLine)
        End If
    End Sub

End Class